<template>
  <div class="second-hand-page">
    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <el-card>
        <div class="filter-container">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索商品名称或描述"
            style="width: 300px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
          
          <el-select
            v-model="filterForm.category"
            placeholder="选择分类"
            style="width: 150px"
            clearable
            @change="handleFilter"
          >
            <el-option label="电子产品" value="电子产品" />
            <el-option label="学习用品" value="学习用品" />
            <el-option label="生活用品" value="生活用品" />
            <el-option label="服装鞋帽" value="服装鞋帽" />
            <el-option label="图书资料" value="图书资料" />
            <el-option label="其他" value="其他" />
          </el-select>

          <el-select
            v-model="filterForm.status"
            placeholder="选择状态"
            style="width: 150px"
            clearable
            @change="handleFilter"
          >
            <el-option label="在售" :value="1" />
            <el-option label="已下架" :value="0" />
            <el-option label="已售出" :value="2" />
          </el-select>

          <el-input-number
            v-model="filterForm.minPrice"
            placeholder="最低价"
            :min="0"
            style="width: 120px"
            @change="handleFilter"
          />
          
          <el-input-number
            v-model="filterForm.maxPrice"
            placeholder="最高价"
            :min="0"
            style="width: 120px"
            @change="handleFilter"
          />

          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>

          <el-button type="primary" @click="handleBackToHome">
            <el-icon><HomeFilled /></el-icon>
            返回Home
          </el-button>

          <!-- 新增：跳转到订单管理页面 -->
          <el-button type="success" @click="handleGoToOrders">
            <el-icon><Document /></el-icon>
            我的订单
          </el-button>

          <!-- 新增：管理我的商品按钮 -->
          <el-button type="warning" @click="handleManageMyGoods">
            <el-icon><Goods /></el-icon>
            管理我的商品
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 商品列表 -->
    <div class="goods-list-section">
      <el-row v-loading="loading" :gutter="16">
        <el-col
          v-for="item in goods"
          :key="item.item_id"
          :xs="24"
          :sm="12"
          :md="6"
          style="margin-bottom: 16px"
        >
          <el-card
            class="good-card"
            :body-style="{ padding: '0' }"
            shadow="hover"
          >
            <!-- 商品图片轮播 -->
            <div class="good-images">
              <el-carousel 
                v-if="getGoodImages(item).length > 0" 
                :interval="3000"
                indicator-position="outside"
                height="200px"
                :loop="true"
                @change="handleCarouselChange"
              >
                <el-carousel-item v-for="(image, index) in getGoodImages(item)" :key="index">
                  <img :src="image" :alt="item.title" class="good-image" @error="handleImageError" />
                </el-carousel-item>
              </el-carousel>
              <div v-else class="no-image">
                <el-icon size="48"><Picture /></el-icon>
                <span>暂无图片</span>
              </div>
            </div>

            <div style="padding: 16px">
              <div class="card-header">
                <h4 class="good-title">{{ item.title }}</h4>
                <div class="card-actions">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button
                      size="small"
                      text
                      @click.stop="handleViewDetail(item.item_id)"
                    >
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <!-- 移除编辑和删除按钮 -->
                </div>
              </div>

              <p class="good-description">{{ truncateDescription(item.description) }}</p>

              <div class="good-info">
                <div class="price-section">
                  <span class="price">¥{{ item.price }}</span>
                </div>
                
                <div class="tags-section">
                  <el-tag :type="getCategoryType(item.category)" size="small">
                    {{ item.category }}
                  </el-tag>
                  <el-tag :type="getStatusType(item.status)" size="small">
                    {{ getStatusText(item.status) }}
                  </el-tag>
                </div>
                
                <div class="seller-info">
                  <el-avatar :src="getFullImageUrl(item.seller?.avatar)" :size="24" />
                  <span style="margin-left: 8px">{{ item.seller?.nickname || '未知用户' }}</span>
                </div>
                
                <div class="create-time">
                  {{ formatTime(item.created_at) }}
                </div>

                <!-- 新增：购买按钮 -->
                <div class="buy-section" style="margin-top: 12px;">
                  <el-button 
                    type="primary" 
                    size="small" 
                    :disabled="item.status !== 1 || isMyGood(item)"
                    @click.stop="handleBuy(item)"
                    style="width: 100%;"
                  >
                    <el-icon><ShoppingCart /></el-icon>
                    {{ isMyGood(item) ? '我的商品' : '立即购买' }}
                  </el-button>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <div v-if="goods.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无商品数据" />
      </div>

      <!-- 分页 -->
      <div v-if="goods.length > 0" class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[4, 8, 12, 24]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 详情模态框 -->
    <DetailModal
      :visible="detailVisible"
      :good="currentGood"
      @cancel="handleDetailCancel"
      @buy="handleBuyFromDetail"
    />

    <!-- 购买确认对话框 -->
    <el-dialog
      v-model="buyDialogVisible"
      title="确认购买"
      width="400px"
      :before-close="handleBuyDialogClose"
    >
      <div v-if="selectedGood" class="buy-dialog-content">
        <div class="good-info">
          <h4>{{ selectedGood.title }}</h4>
          <p class="price">价格: ¥{{ selectedGood.price }}</p>
          <p class="seller">卖家: {{ selectedGood.seller?.nickname }}</p>
        </div>
        <el-form :model="buyForm" label-width="80px">
          <el-form-item label="购买数量">
            <el-input-number
              v-model="buyForm.quantity"
              :min="1"
              :max="1"
              :disabled="true"
            />
            <span style="margin-left: 8px; color: #999;">二手商品仅支持购买1件</span>
          </el-form-item>
          <el-form-item label="总金额">
            <span class="total-amount">¥{{ (selectedGood.price * buyForm.quantity).toFixed(2) }}</span>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="handleBuyDialogClose">取消</el-button>
        <el-button type="primary" :loading="buyLoading" @click="handleConfirmBuy">
          确认购买
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search,
  Picture,
  View,
  Refresh,
  HomeFilled,
  Document,
  ShoppingCart,
  Goods
} from '@element-plus/icons-vue';
import { goodApi } from '@/api/good';
import { orderApi } from '@/api/order'; // 新增订单API
import DetailModal from '@/components/goods/DetailModal.vue';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const userStore = useUserStore();

// 响应式数据
const loading = ref(false);
const goods = ref([]);
const searchKeyword = ref('');
const detailVisible = ref(false);
const currentGood = ref(null);
const buyDialogVisible = ref(false);
const buyLoading = ref(false);
const selectedGood = ref(null);

// 购买表单
const buyForm = reactive({
  quantity: 1
});

// 筛选表单
const filterForm = reactive({
  category: '',
  status: '',
  minPrice: undefined,
  maxPrice: undefined
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 4,
  total: 0
});

// 计算当前用户ID
const currentUserId = computed(() => userStore.userInfo?.user_id);

// 检查是否为当前用户的商品
const isMyGood = (good) => {
  return good.user_id === currentUserId.value;
};

// 获取完整的图片URL
const getFullImageUrl = (url) => {
  if (!url) return '';
  if (url.startsWith('http') || url.startsWith('//') || url.startsWith('blob:')) {
    return url;
  }
  const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:7001';
  if (url.startsWith('/public/')) {
    return `${baseUrl}${url}`;
  }
  return url.startsWith('/') ? `${baseUrl}${url}` : `${baseUrl}/${url}`;
};

// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src);
  event.target.src = '';
};

// 处理商品图片数据
const getGoodImages = (good) => {
  if (!good || !good.images) return [];
  let imageUrls = [];
  if (Array.isArray(good.images)) {
    imageUrls = good.images.filter(url => url && url.trim());
  } else if (typeof good.images === 'string') {
    if (good.images.includes(',')) {
      imageUrls = good.images.split(',').filter(url => url && url.trim());
    } else if (good.images.trim()) {
      imageUrls = [good.images.trim()];
    }
  }
  const fullUrls = imageUrls.map(url => getFullImageUrl(url));
  return fullUrls;
};

// 轮播图切换处理
const handleCarouselChange = (currentIndex, prevIndex) => {
  console.log(`轮播图从 ${prevIndex} 切换到 ${currentIndex}`);
};

// 截断描述文本
const truncateDescription = (description) => {
  if (!description) return '';
  const desc = String(description);
  return desc.length > 50 ? desc.substring(0, 50) + '...' : desc;
};

// 分类类型映射
const getCategoryType = (category) => {
  const types = {
    '电子产品': 'primary',
    '学习用品': 'success',
    '生活用品': 'warning',
    '服装鞋帽': 'danger',
    '图书资料': 'info',
    '其他': ''
  };
  return types[category] || '';
};

// 状态类型映射
const getStatusType = (status) => {
  const types = {
    1: 'success',  // 在售
    0: 'warning',  // 已下架
    2: 'info'      // 已售出
  };
  return types[status] || '';
};

// 状态文本映射
const getStatusText = (status) => {
  const texts = {
    1: '在售',
    0: '已下架',
    2: '已售出'
  };
  return texts[status] || '未知状态';
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  return new Date(time).toLocaleDateString();
};

// 处理 token 过期的统一方法
const handleTokenExpired = async (error) => {
  if (error.response && error.response.data && error.response.data.msg) {
    const errorMsg = error.response.data.msg;
    if (errorMsg.includes('登录已过期') || errorMsg.includes('无效的token') || errorMsg.includes('认证失败')) {
      ElMessage.error('登录已过期，请重新登录');
      userStore.logout();
      router.push('/login');
      return true;
    }
  }
  return false;
};

// 加载商品列表
const loadGoods = async () => {
  try {
    loading.value = true;
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...filterForm
    };

    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === '') {
        delete params[key];
      }
    });

    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
    }

    const response = await goodApi.list(params);
    
    if (response.code === 0) {
      goods.value = response.data.list;
      pagination.total = response.data.pagination.total;
    } else {
      ElMessage.error(response.msg || '获取列表失败');
      goods.value = [];
    }
  } catch (error) {
    console.error('加载商品列表失败:', error);
    const isTokenExpired = await handleTokenExpired(error);
    if (!isTokenExpired) {
      ElMessage.error('网络错误，请重试');
    }
    goods.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.current = 1;
  loadGoods();
};

// 筛选处理
const handleFilter = () => {
  pagination.current = 1;
  loadGoods();
};

// 重置筛选
const handleReset = () => {
  searchKeyword.value = '';
  filterForm.category = '';
  filterForm.status = '';
  filterForm.minPrice = undefined;
  filterForm.maxPrice = undefined;
  pagination.current = 1;
  loadGoods();
};

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.current = 1;
  loadGoods();
};

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.current = page;
  loadGoods();
};

// 返回Home
const handleBackToHome = () => {
  router.push('/');
};

// 跳转到订单管理
const handleGoToOrders = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  router.push('/orders');
};

// 管理我的商品
const handleManageMyGoods = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  router.push('/mygoods');
};

// 查看详情
const handleViewDetail = async (goodId) => {
  try {
    const response = await goodApi.detail(goodId);
    if (response.code === 0) {
      currentGood.value = response.data;
      detailVisible.value = true;
    } else {
      ElMessage.error(response.msg || '获取详情失败');
    }
  } catch (error) {
    console.error('获取商品详情失败:', error);
    const isTokenExpired = await handleTokenExpired(error);
    if (!isTokenExpired) {
      ElMessage.error('网络错误，请重试');
    }
  }
};

// 购买商品
const handleBuy = (good) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }

  if (isMyGood(good)) {
    ElMessage.warning('不能购买自己的商品');
    return;
  }

  if (good.status !== 1) {
    ElMessage.warning('商品已下架或已售出');
    return;
  }

  selectedGood.value = good;
  buyForm.quantity = 1;
  buyDialogVisible.value = true;
};

// 从详情页购买
const handleBuyFromDetail = (good) => {
  detailVisible.value = false;
  handleBuy(good);
};

// 确认购买
const handleConfirmBuy = async () => {
  if (!selectedGood.value) return;

  try {
    buyLoading.value = true;
    
    const orderData = {
      seller_id: selectedGood.value.user_id,
      goods_id: selectedGood.value.item_id,
      amount: selectedGood.value.price * buyForm.quantity
    };

    const response = await orderApi.create(orderData);
    
    if (response.code === 0) {
      ElMessage.success('购买成功！');
      buyDialogVisible.value = false;
      selectedGood.value = null;
      // 刷新商品列表
      loadGoods();
    } else {
      ElMessage.error(response.msg || '购买失败');
    }
  } catch (error) {
    console.error('购买失败:', error);
    const isTokenExpired = await handleTokenExpired(error);
    if (!isTokenExpired) {
      ElMessage.error('购买失败，请重试');
    }
  } finally {
    buyLoading.value = false;
  }
};

// 关闭购买对话框
const handleBuyDialogClose = () => {
  buyDialogVisible.value = false;
  selectedGood.value = null;
  buyForm.quantity = 1;
};

// 详情模态框取消
const handleDetailCancel = () => {
  detailVisible.value = false;
  currentGood.value = null;
};

// 初始化加载
onMounted(() => {
  console.log('二手商品页面已加载');
  loadGoods();
});
</script>

<style scoped>
.second-hand-page {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.search-filter-section {
  margin-bottom: 24px;
}

.filter-container {
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.goods-list-section {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  min-height: 400px;
}

.good-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  height: 100%;
}

.good-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.good-images {
  height: 200px;
  overflow: hidden;
  position: relative;
}

.good-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  display: block;
}

.no-image {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #999;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
}

.good-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  flex: 1;
  margin-right: 8px;
}

.card-actions {
  display: flex;
  gap: 4px;
}

.good-description {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
  margin: 0 0 12px 0;
}

.good-info {
  margin-top: 12px;
}

.good-info > div {
  margin-bottom: 8px;
}

.price-section {
  display: flex;
  align-items: center;
}

.price {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
}

.tags-section {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.seller-info {
  display: flex;
  align-items: center;
  margin: 8px 0;
}

.create-time {
  color: #909399;
  font-size: 12px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.buy-dialog-content .good-info {
  text-align: center;
  margin-bottom: 20px;
}

.buy-dialog-content .price {
  font-size: 20px;
  color: #ff4d4f;
  font-weight: bold;
}

.buy-dialog-content .seller {
  color: #666;
}

.total-amount {
  font-size: 18px;
  color: #ff4d4f;
  font-weight: bold;
}

:deep(.el-carousel__indicators--outside) {
  bottom: -30px;
}

:deep(.el-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.3);
}

:deep(.el-carousel__arrow:hover) {
  background-color: rgba(0, 0, 0, 0.5);
}

:deep(.el-carousel) {
  position: relative;
}

:deep(.el-carousel__container) {
  position: relative;
  height: 200px;
}

:deep(.el-carousel__item) {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: inline-block;
  overflow: hidden;
  z-index: 0;
}

:deep(.el-carousel__item.is-active) {
  z-index: 2;
}

:deep(.el-carousel__item.is-animating) {
  transition: transform 0.4s ease-in-out;
}
</style>